<?php

namespace app\admin\controller\wanlshop;

use app\admin\model\wanlshop\Industy;
use app\api\controller\wanlshop\Separate;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{
    
    /**
     * Shop模型对象
     * @var \app\admin\model\wanlshop\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Shop;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
    
            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
    
            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['username']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
    
            return json($result);
        }
        return $this->view->fetch();
    }
//    public function edit($ids = NULL)
//    {
//        $shop_id = $this->request->request('shop_id');
//        $row = $this->model->get($shop_id);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
//        $this->view->assign("row", $row);
//        return $this->view->fetch();
//    }
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('id', $ids);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if($params['qualification_type']){
                $industy = Industy::where('id',$params['qualification_type'])->find();
                $params['qualification_type'] = $industy['industry_name'];
            }
            if(!isset($params['license_period_end'])){
                $params['license_period_end'] = '长期';
            }
            if(!isset($params['contact_period_end'])){
                $params['contact_period_end'] = '长期';
            }
            if(!isset($params['certificate_period_end'])){
                $params['certificate_period_end'] = '长期';
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function endpoint()
    {
        $shop_id = $this->request->post('shop_id');
        $row = $this->model->get($shop_id);
        $separte = new Separate();
        $res = $separte->QueryApply($row['applyment_id']);
        if(isset($res['sub_mchid'])){
            $this->model->where('id',$shop_id)->update([
                'sub_mchid'=>$res['sub_mchid']
            ]);
        }

        switch ($res['applyment_state']){
            case 'APPLYMENT_STATE_EDITTING':
                $text = '编辑中,提交申请发生错误导致，请尝试重新提交';
                break;
            case 'APPLYMENT_STATE_AUDITING':
                $text = '审核中';
                break;
            case 'APPLYMENT_STATE_REJECTED':
                if($res['applyment_state_msg']){
                    $msg = $res['applyment_state_msg'];
                }else{
                    $msg = $res['audit_detail'][0]['reject_reason'];
                }
                $this->model->where('id',$shop_id)->update([
                    'status'=>'hidden'
                ]);
                $text = '已驳回,'.$msg;
                break;
            case 'APPLYMENT_STATE_TO_BE_CONFIRMED':
                $text = '待账户验证';
                break;
            case 'APPLYMENT_STATE_TO_BE_SIGNED':
                $text = '待签约';
                break;
            case 'APPLYMENT_STATE_SIGNING':
                $text = '开通权限中';
                break;
            case 'APPLYMENT_STATE_FINISHED':
                $text = '已完成';
                break;
        }
        $this->success($text);
    }
    public function application()
    {
        $shop_id = $this->request->post('shop_id');
        $separte = new Separate();
        $separte->application($shop_id);
        $this->success();
    }
    public function category(){
        $keywords = $this->request->post('name');
        $page = $this->request->post('pageNumber', 1);
        $query = \app\admin\model\wanlshop\Category::where('pid',0)->where('type','goods');
        if (!empty($keywords)) {
            $query->whereLike('name', "%$keywords%");
        }

        $keyValue = $this->request->post('keyValue', null);
        if ($keyValue !== null) {
            $query->where('id', $keyValue);
        }
        $list = $query->select();
        $result = [
            'code' => 0,
            'msg' => '获取成功',
//            'total' => $list['total'],
            'list' => $list
        ];

        return json($result);
    }
    public function qualification_type(){
        $keywords = $this->request->post('name');
        $page = $this->request->post('pageNumber', 1);
        $query = Industy::where('level',2);
        if (!empty($keywords)) {
            $query->whereLike('industry_name', "%$keywords%");
        }

        $keyValue = $this->request->post('keyValue', null);
        if ($keyValue !== null) {
            $query->where('industry_name', $keyValue);
        }
        $list = $query->select();
        $result = [
            'code' => 0,
            'msg' => '获取成功',
//            'total' => $list['total'],
            'list' => $list
        ];

        return json($result);
    }
}
